local Data "Demographic"

noi disp "Obtaining `Data' data..."
noi disp "Verifying that `Data' does not already exist..."
* This returns an error if the file does not exist.
capture confirm file "`Data'.dta"

* If an error is returned, then the commands below are run.
if _rc == 601 {
	noi disp "Data not found.  Building data..."
	noi disp "Loading demographic_data.csv..."
	insheet using "$SourceData\demographic_data.csv", clear
	noi disp "Building Demographic.dta..."

	sort geography year
	* Verify that there are no duplicates by geography and year.
	isid geography year

	merge 1:1 geography year using "$SourceData\County_HPI.dta"
	
	drop if _merge==2
	drop _merge
	sort geography year
	xtset geography year

	gen temp = ln_pop - L2.ln_pop if year==2002 
	bysort geography: egen pop2000_2002 = max(temp)
	drop temp

	gen temp = exp(ln_pop) if year==2000 
	bysort geography: egen pop2000 = max(temp)
	drop temp

	gen temp = ln(income) if year==2000 
	bysort geography: egen lnincome2000 = max(temp)
	drop temp
	
	gen temp = ln(income) - ln(L2.income) if year==2002
	bysort geography: egen inc2000_2002 = max(temp)
	drop temp

	gen temp = unem - L2.unem if year==2002
	bysort geography: egen unem2000_2002 = max(temp)
	drop temp

	gen lngdp = ln(income*exp(ln_pop))
	gen temp = lngdp - L2.lngdp if year==2002
	gen dlngdp = lngdp - L.lngdp
	bysort geography: egen lngdp2000_2002 = max(temp)
	drop temp
	
	gen temp  = (hpiwith2000base - L2.hpiwith2000base)/L2.hpiwith2000base if year==2002
	bysort geography: egen hpi2000_2002 = max(temp)
	drop temp

	
	noi disp "Saving `Data'.dta"
	compress
	save "$LocalData\\`Data'.dta", replace
	save "$LocalData\Archive\\`Data'`CurrentDate'.dta", replace
}
* This runs if no error was returned.
else noi disp "`Data' already exists."
noi etime
noi disp " "
	